//
//  DDErandChangeListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-6.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "DDErandChangeListViewController.h"
#import "DDErandChangeViewController.h"
#import "CommonDatePickerViewController.h"

@interface DDErandChangeListViewController () <CommonDatePickerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *searchContentView;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UILabel *beginDateLbl;
@property (weak, nonatomic) IBOutlet UILabel *endDateLbl;

@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;
@property (nonatomic, strong) NSMutableArray *erandList;
@property (nonatomic, assign) NSInteger selectedRow;

@property (nonatomic, strong) CommonDatePickerViewController *datePicker;
@property (nonatomic, assign) int dateType; //1表示起始时间，2表示结束时间

- (IBAction)searchErandAction:(id)sender;
- (IBAction)selectDateAction:(id)sender;

@end

@implementation DDErandChangeListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.erandList = [[NSMutableArray alloc] init];
    self.dateType = -1;
    
    [self initHUD];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshViewByReloadData {
    [self queryErandChangeList];
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    
    self.title = @"变更列表";
    
    [super viewWillAppear:animated];
    
    
    [self performSelector:@selector(queryErandChangeList) withObject:nil afterDelay:0.3];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

//查询可变更的申请列表
- (void)queryErandChangeList {
    if (!self.isRefreshing) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:showUpdateAppList parameter:param delegate:self];
        [self.HUD show:YES];
        self.isRefreshing = YES;
    }
}

- (IBAction)searchErandAction:(id)sender {
    NSString *startDate = self.beginDateLbl.text;
    NSString *endDate = self.endDateLbl.text;
    if ([startDate length] == 0 || [startDate isEqual:@"起始时间"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请选择起始时间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([endDate length] == 0 || [endDate isEqual:@"结束时间"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请选择结束时间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        
        self.startTime = startDate;
        self.endTime = endDate;
        
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               self.startTime,@"startTime",
                               self.endTime,@"endTime",
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:showUpdateAppListByTime parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

- (IBAction)selectDateAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    self.datePicker = (CommonDatePickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonDatePicker"];
    _datePicker.delegate = self;
    _datePicker.view.tag = tag;
    
    AppDelegate *app = [AppDelegate sharedDelegate];
    _datePicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame),
                                        CGRectGetHeight(self.view.bounds));
    
    [app.window addSubview:_datePicker.view];
}

#pragma mark - CommonDatePickerDelegate
- (void)picker:(CommonDatePickerViewController *)picker didSelectedDate:(NSDate *)date {
    if (date != nil) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [formatter stringFromDate:date];
        
        NSInteger tag = picker.view.tag;
        if (tag == 100) { //起始时间
            self.beginDateLbl.text = strDate;
        } else if (tag == 101) {
            self.endDateLbl.text = strDate;
        }
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == showUpdateAppList) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    [self.erandList removeAllObjects];
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *results = [dataObject objectForKeyOrNil:@"updateAppList"];
                        if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                            [self.erandList addObjectsFromArray:results];
                        }
                    }
                }
                
                [self.tableView reloadData];
            }
            
        }
    } else if (methodId == showUpdateAppListByTime) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) { //请求成功
                if ([data count] > 0) {
                    [self.erandList removeAllObjects];
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *results = [dataObject objectForKeyOrNil:@"updateAppListByTime"];
                        if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                            [self.erandList addObjectsFromArray:results];
                        }
                    }
                }
                
                [self.tableView reloadData];
            }
            
        }
    }
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == showUpdateAppList) {
                msg = @"出差申请变更列表获取失败，请稍后重试";
            } else if (methodId == showUpdateAppListByTime) {
                msg = @"出差申请变更列表查询失败，请稍后重试";
            }
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - IBAction methods
- (void)selectRowAction:(id)sender event:(id)event {
    NSSet *touches = [event allTouches];
	UITouch *touch = [touches anyObject];
	CGPoint currentTouchPosition = [touch locationInView:self.tableView];
	NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
	if (indexPath == nil) {
		return;
	}
    int row = indexPath.row;
    
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    if (tag == 107) { //状态按钮
        
        self.selectedRow = row;
        
        if ([self.erandList count] > row) {
            NSDictionary *cellData = [self.erandList objectAtIndex:row];
            
            BOOL rejected = [[cellData objectForKeyOrNil:@"bgbh"] boolValue]; //是否驳回
            
            if (rejected) { //驳回状态
                NSString *reason = [cellData objectForKeyOrNil:@"bgbhly"];
                if ([reason length] > 0) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"驳回理由"
                                                                    message:reason
                                                                   delegate:self
                                                          cancelButtonTitle:@"修改"
                                                          otherButtonTitles:@"确定",nil];
                    alert.tag = 1007;
                    [alert show];
                } else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"驳回理由"
                                                                    message:@"未知理由驳回"
                                                                   delegate:self
                                                          cancelButtonTitle:@"修改"
                                                          otherButtonTitles:@"确定",nil];
                    alert.tag = 1007;
                    [alert show];
                }
            } else {
                DDErandChangeViewController *changeVC = (DDErandChangeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandChangeDetail"];
                if ([self.erandList count] > row) {
                    NSDictionary *cellData = [self.erandList objectAtIndex:row];
                    changeVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
                }
                [self.navigationController pushViewController:changeVC animated:YES];
            }
        }
    }
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1007) {
        if (buttonIndex == alertView.cancelButtonIndex) {
            if ([self.erandList count] > self.selectedRow && 0 <= self.selectedRow) {
                DDErandChangeViewController *changeVC = (DDErandChangeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandChangeDetail"];
                NSDictionary *cellData = [self.erandList objectAtIndex:self.selectedRow];
                changeVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
                [self.navigationController pushViewController:changeVC animated:YES];
            }
        }
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.erandList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsChangeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *userNameLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *userIDLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *agencyNameLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *agencyCodeLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *reasonLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:107];
    
    [statusBtn addTarget:self action:@selector(selectRowAction:event:) forControlEvents:UIControlEventTouchUpInside];
    
    NSInteger row = indexPath.row;
    
    if ([self.erandList count] > row) {
        NSDictionary *cellData = [self.erandList objectAtIndex:row];
        
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *merchantName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *merchantCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *merchantbgName = [cellData objectForKeyOrNil:@"bgjxsmc"];
        NSString *merchantbgCode = [cellData objectForKeyOrNil:@"bgjxsdm"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *bgreason = [cellData objectForKeyOrNil:@"bgmd"];
        NSString *time = [cellData objectForKeyOrNil:@"ccsj"];
       
        BOOL sfbg = [[cellData objectForKeyOrNil:@"sfbg"] boolValue]; //是否变更
        BOOL bgbh = [[cellData objectForKeyOrNil:@"bgbh"] boolValue]; //是否驳回
        BOOL bgshzt = [[cellData objectForKeyOrNil:@"bgshzt"] boolValue]; //变更审核
        userNameLbl.text = dudaoName;
        userIDLbl.text = dudaoCode;
        agencyNameLbl.text = merchantName;
        agencyCodeLbl.text = merchantCode;
        reasonLbl.text = reason;
        dateLbl.text = time;
        NSLog(@"@@@@@@@@@%d",sfbg);
        if(sfbg){
            agencyNameLbl.text = merchantbgName;
            agencyCodeLbl.text = merchantbgCode;
            reasonLbl.text = bgreason;
        }
        /*
         if(!item.isBgbh()&&!item.isBgshzt()&&!item.isSfbg()){
         item_btn.setText("待修改");
         item_btn.setBackgroundResource(R.drawable.dxg);
         }
         if(item.isBgbh()&&!item.isBgshzt()&&!item.isSfbg()){
         item_btn.setText("未通过");
         item_btn.setBackgroundResource(R.drawable.tip_unpass);
         }
         if(item.isBgbh()&&!item.isBgshzt()&&item.isSfbg()){
         item_btn.setText("驳回");
         item_btn.setBackgroundResource(R.drawable.tip_reject);
         }
         if(item.isBgbh()&&item.isBgshzt()&&!item.isSfbg()){
         item_btn.setText("通过");
         item_btn.setBackgroundResource(R.drawable.tip_pass);
         }
         */
        
        if (!bgbh && !bgshzt && !sfbg) {
            [statusBtn setTitle:@"待修改" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_待审核.png"] forState:UIControlStateNormal];
        }
        if (!bgbh && !bgshzt && sfbg) {
            NSString *ldxm = [cellData objectForKeyOrNil:@"bgldxm"];
            NSString *statusText = [@"待审核\n" stringByAppendingString:ldxm];
            [statusBtn setTitle:statusText forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_未通过.png"] forState:UIControlStateNormal];
            statusBtn.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
            statusBtn.frame = CGRectMake(218, 32, 66, 40);
        }
        if (bgbh && !bgshzt && !sfbg) {
            [statusBtn setTitle:@"驳回" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_驳回.png"] forState:UIControlStateNormal];
        }
        if (!bgbh && bgshzt && sfbg) {
            [statusBtn setTitle:@"通过" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
        }
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    NSDictionary *cellData = [self.erandList objectAtIndex:row];
    BOOL sfbg = [[cellData objectForKeyOrNil:@"sfbg"] boolValue]; //是否变更
    BOOL bgbh = [[cellData objectForKeyOrNil:@"bgbh"] boolValue]; //是否驳回
    BOOL bgshzt = [[cellData objectForKeyOrNil:@"bgshzt"] boolValue]; //变更审核
    if (!bgbh && !bgshzt && sfbg) {
        return 75.0;
    }else
        return 60.0;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    DDErandChangeViewController *changeVC = (DDErandChangeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandChangeDetail"];
    if ([self.erandList count] > row) {
        NSDictionary *cellData = [self.erandList objectAtIndex:row];
        changeVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
    }
    [self.navigationController pushViewController:changeVC animated:YES];
}

@end
